﻿using System;
using System.Windows.Forms;
using Raven.Client.Document;
using Sponsorship.Domain;
using Sponsorship.Infrastructure;
using Sponsorship.Infrastructure.BootStrapping;
using Sponsorship.ReadModel;
using StructureMap;

namespace Sponsorship.Ui
{
    internal static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        public static void Main()
        {
            Form1 mainForm;
            try
            {
                InitializeInfrastructure();

                //var bus = ObjectFactory.GetInstance<IBus>();

                //bus.Send(new EnterSponsor(Guid.NewGuid(), null, null, null, null,null,null,null));
                //bus.Send(new EnterSponsor(Guid.NewGuid(), null, null, null, null, null, null, null));

                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                mainForm = ObjectFactory.GetInstance<Form1>();
            }
            catch (Exception ex)
            {
                MessageBox.Show (ex.ToString(), "Fatal error while initializing the application");
                throw;
            }

            Application.ThreadException += (sender, args) => MessageBox.Show (args.Exception.ToString(), "Error on background thread");

            try
            {
                Application.Run(mainForm);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Fatal error while running the application");
                throw;
            }
        }

        private static void InitializeInfrastructure()
        {
            //use RavenDB Server as an event store and persists the read side (views) also to RavenDB Server
            var viewStore = new DocumentStore {ConnectionStringName = BootStrapper.RavenDbConnectionStringName};
            viewStore.Initialize();

            var consistentViewStore = new QueryYourWritesDocumentStoreDecorator (viewStore);

            IContainer container = BootStrapper.BootStrap (consistentViewStore);
        }
    }
}